#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <string>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    //父进程创建管道，子进程写入，父进程读取
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    (void)n; //防止编译的时候有告警
    //fork函数创建父子进程
    pid_t id = fork();
    if(id < 0){
        perror("perror fork!\n");
        exit(1);
    }else if(id == 0) {
        //子进程创建成功，关闭子进程读
        int close[pipefd[0]];
        int count = 0;
        std::string message = "hello,I am child process,";
        std::string str = std::to_string(getpid());
        while(1)
        {
            message += "pipefd[1]:" + str + "," + std::to_string(count++);
            message += "\t\n";
            write(pipefd[1],message.c_str(),message.size());
            sleep(2);
        }
    }else {
        //关闭父进程写
        int close[pipefd[1]];

        while(1)
        {
            char buffer[1024];
            ssize_t n = read(pipefd[0],buffer,sizeof(buffer)-1);
            if(n > 0){
                buffer[n] = 0;
                std::cout << "clint -> father#" << " " << buffer <<std::endl;
            }
        }

        pid_t rit = waitpid(id, nullptr, 0);
        (void)rit;
    }
    //正常运行

    return 0;
}